/*
 * Copyright 2020 tu.cn All right reserved. This software is the
 * confidential and proprietary information of tu.cn ("Confidential
 * Information"). You shall not disclose such Confidential Information and shall
 * use it only in accordance with the terms of the license agreement you entered
 * into with Tu.cn
 */
package com.onedec.utils;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.web.servlet.ModelAndView;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 31014
 * @date 2020/7/9 17:09
 */
public class ExceptionCodeMapping {
    private static Map<String,String> exceptionMapping = new HashMap<>();

    static {
        SAXReader reader = new SAXReader();
        String substring = ModelAndView.class.getResource("/").getPath().substring(1);
        System.out.println(substring);
        try {
            Document document = reader.read(substring + "exception-config.xml");
            Element rootElement = document.getRootElement();
            List<Element> exceptions = rootElement.elements("exception");
            for (Element exception : exceptions) {
                String code = exception.attributeValue("code");
                String clazz = exception.attributeValue("class");
                exceptionMapping.put(code,clazz);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    public static void isException(ResponseEntity responseEntity){
        if ("200".equals(responseEntity.getCode())){
            return;
        }else {
            final String clazz = exceptionMapping.get(responseEntity.getCode());
             Class<?> c=null;
            try {
                c = Class.forName(clazz);
                throw (RuntimeException) c.newInstance();
            } catch (ClassNotFoundException | IllegalAccessException | InstantiationException e) {
                e.printStackTrace();
            }

        }
    }

}